package com.rainkaze.lifeharbor.tools.bingwallpaper;

import android.app.DatePickerDialog;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.ActivityToolWallpaperBingBinding;
import com.rainkaze.lifeharbor.tools.bingwallpaper.adapter.WallpaperAdapter;
import com.rainkaze.lifeharbor.tools.bingwallpaper.model.BingWallpaperResponse;
import com.rainkaze.lifeharbor.tools.bingwallpaper.model.WallpaperItem;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class BingWallpaperActivity extends AppCompatActivity {

    private static final String TAG = "BingWallpaperActivity";
    private static final String API_BASE_URL = "https://raw.onmicrosoft.cn/Bing-Wallpaper-Action/main/data/%s.json";
    private static final int INITIAL_LOAD_COUNT = 10; // 初始加载数量
    private static final int LOAD_MORE_COUNT = 10;   // 向下滑动加载更多数量

    private ActivityToolWallpaperBingBinding binding;
    private OkHttpClient okHttpClient;
    private Gson gson;
    private WallpaperAdapter wallpaperAdapter;
    private List<WallpaperItem> allWallpapersForSelectedLang = new ArrayList<>();
    private List<WallpaperItem> displayedWallpapers = new ArrayList<>();
    private boolean isLoading = false;
    private int currentPage = 0;
    private String currentSelectedLanguage = "zh-CN_all";
    private String selectedDateForQuery = null;

    private final String[] languageCodes = {"zh-CN_all", "en-US_all", "ja-JP_all"};
    private final String[] languageNames = {"中文", "英文", "日文"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityToolWallpaperBingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        okHttpClient = new OkHttpClient();
        gson = new Gson();

        setupToolbar();
        setupLanguageSpinner();
        setupRecyclerView();
        setupDatePickerButton();

        fetchWallpapersForLanguage(currentSelectedLanguage, true);
    }

    private void setupToolbar() {
        setSupportActionBar(binding.toolbarBingWallpaper);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupLanguageSpinner() {
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_dropdown_item, languageNames);
        binding.spinnerLanguageBing.setAdapter(spinnerAdapter);
        binding.spinnerLanguageBing.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentSelectedLanguage = languageCodes[position];
                selectedDateForQuery = null;
                updateSelectedDateTextView();
                Log.d(TAG, "语言已选择: " + currentSelectedLanguage);
                fetchWallpapersForLanguage(currentSelectedLanguage, true);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void setupRecyclerView() {
        wallpaperAdapter = new WallpaperAdapter(this, displayedWallpapers);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1); // 每行1个
        binding.recyclerViewWallpapersBing.setLayoutManager(gridLayoutManager);
        binding.recyclerViewWallpapersBing.setAdapter(wallpaperAdapter);

        binding.recyclerViewWallpapersBing.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null && !isLoading && selectedDateForQuery == null) {
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount - (LOAD_MORE_COUNT / 2) && firstVisibleItemPosition >= 0) {
                        loadMoreWallpapers();
                    }
                }
            }
        });
    }

    private void setupDatePickerButton() {
        binding.buttonPickDateBing.setOnClickListener(v -> {
            final Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    (view, yearSelected, monthOfYear, dayOfMonth) -> {
                        selectedDateForQuery = String.format(Locale.getDefault(), "%d%02d%02d", yearSelected, monthOfYear + 1, dayOfMonth);
                        Log.d(TAG, "日期已选择: " + selectedDateForQuery);
                        updateSelectedDateTextView();
                        filterAndDisplayByDate();
                    }, year, month, day);
            datePickerDialog.show();
        });
    }

    private void updateSelectedDateTextView() {
        if (selectedDateForQuery != null) {
            try {
                SimpleDateFormat querySdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
                SimpleDateFormat displaySdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                Date date = querySdf.parse(selectedDateForQuery);
                if (date != null) {
                    binding.textViewSelectedDateBing.setText("当前查询日期: " + displaySdf.format(date));
                    binding.textViewSelectedDateBing.setVisibility(View.VISIBLE);
                }
            } catch (ParseException e) {
                Log.e(TAG, "解析选中日期时出错", e);
                binding.textViewSelectedDateBing.setText("日期格式错误");
                binding.textViewSelectedDateBing.setVisibility(View.VISIBLE);
            } catch (java.text.ParseException e) {
                throw new RuntimeException(e);
            }
        } else {
            binding.textViewSelectedDateBing.setText("当前显示近期图片");
            binding.textViewSelectedDateBing.setVisibility(View.VISIBLE);
        }
    }


    private void fetchWallpapersForLanguage(String languageCode, boolean clearPrevious) {
        if (isLoading) return;
        isLoading = true;
        showLoadingState(true);
        if (clearPrevious) {
            allWallpapersForSelectedLang.clear();
            displayedWallpapers.clear();
            wallpaperAdapter.notifyDataSetChanged();
            currentPage = 0;
        }

        String apiUrl = String.format(API_BASE_URL, languageCode);
        Log.d(TAG, "请求壁纸 API URL: " + apiUrl);

        Request request = new Request.Builder().url(apiUrl).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取壁纸数据失败: ", e);
                runOnUiThread(() -> {
                    isLoading = false;
                    showLoadingState(false);
                    showErrorState("网络请求失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        Log.e(TAG, "API 响应体为空");
                        runOnUiThread(() -> {
                            isLoading = false;
                            showLoadingState(false);
                            showErrorState("获取壁纸失败: 服务器响应为空");
                        });
                        return;
                    }
                    responseBodyString = responseBody.string();
                }

                if (!response.isSuccessful()) {
                    Log.e(TAG, "API 请求未成功: " + response.code() + " " + response.message());
                    runOnUiThread(() -> {
                        isLoading = false;
                        showLoadingState(false);
                        showErrorState("获取壁纸失败 (HTTP " + response.code() + ")");
                    });
                    return;
                }

                Log.d(TAG, "壁纸 API 响应 (部分): " + (responseBodyString.length() > 300 ? responseBodyString.substring(0, 300) + "..." : responseBodyString));
                runOnUiThread(() -> {
                    isLoading = false;
                    showLoadingState(false);
                    try {
                        BingWallpaperResponse bingResponse = gson.fromJson(responseBodyString, BingWallpaperResponse.class);
                        if (bingResponse != null && bingResponse.isSuccess() && bingResponse.getData() != null) {
                            allWallpapersForSelectedLang.clear(); // 每次获取完整列表
                            allWallpapersForSelectedLang.addAll(bingResponse.getData());
                            Log.d(TAG, "成功获取 " + allWallpapersForSelectedLang.size() + " 张壁纸 for " + languageCode);
                            if (selectedDateForQuery != null) {
                                filterAndDisplayByDate();
                            } else {
                                loadInitialWallpapers();
                            }
                        } else {
                            String msg = bingResponse != null ? bingResponse.getMessage() : "响应数据格式错误";
                            Log.e(TAG, "API 业务错误或数据无效: " + msg);
                            showErrorState("获取壁纸失败: " + msg);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "JSON 解析错误: ", e);
                        showErrorState("数据解析失败");
                    }
                });
            }
        });
    }

    private void loadInitialWallpapers() {
        displayedWallpapers.clear();
        currentPage = 0;
        int end = Math.min(INITIAL_LOAD_COUNT, allWallpapersForSelectedLang.size());
        if (end > 0) {
            displayedWallpapers.addAll(allWallpapersForSelectedLang.subList(0, end));
            currentPage = end;
        }
        wallpaperAdapter.notifyDataSetChanged();
        binding.recyclerViewWallpapersBing.setVisibility(View.VISIBLE);
        binding.textViewErrorBing.setVisibility(View.GONE);
        if (displayedWallpapers.isEmpty()) {
            showErrorState("当前语言下没有近期壁纸。");
        }
    }

    private void loadMoreWallpapers() {
        if (isLoading || selectedDateForQuery != null) return;

        if (currentPage >= allWallpapersForSelectedLang.size()) {
            Log.d(TAG, "已加载全部图片 for " + currentSelectedLanguage);
            return;
        }

        isLoading = true;

        int start = currentPage;
        int end = Math.min(currentPage + LOAD_MORE_COUNT, allWallpapersForSelectedLang.size());

        if (start < end) {
            List<WallpaperItem> nextPageItems = allWallpapersForSelectedLang.subList(start, end);
            displayedWallpapers.addAll(nextPageItems);
            wallpaperAdapter.notifyItemRangeInserted(start, nextPageItems.size());
            currentPage = end;
        }
        isLoading = false;
        Log.d(TAG, "加载更多: " + displayedWallpapers.size() + " / " + allWallpapersForSelectedLang.size());
    }

    private void filterAndDisplayByDate() {
        if (selectedDateForQuery == null || allWallpapersForSelectedLang.isEmpty()) {
            if (allWallpapersForSelectedLang.isEmpty() && selectedDateForQuery != null) {
                fetchWallpapersForLanguage(currentSelectedLanguage, true);
            } else {
                loadInitialWallpapers();
            }
            return;
        }

        isLoading = true;
        displayedWallpapers.clear();
        boolean found = false;
        for (WallpaperItem item : allWallpapersForSelectedLang) {
            if (selectedDateForQuery.equals(item.getStartdate())) {
                displayedWallpapers.add(item);
                found = true;
                break;
            }
        }
        wallpaperAdapter.notifyDataSetChanged();
        isLoading = false;

        if (found) {
            binding.recyclerViewWallpapersBing.setVisibility(View.VISIBLE);
            binding.textViewErrorBing.setVisibility(View.GONE);
            Toast.makeText(this, "已显示 " + selectedDateForQuery + " 的壁纸", Toast.LENGTH_SHORT).show();
        } else {
            showErrorState("未找到日期 " + selectedDateForQuery + " 的壁纸。");
            Toast.makeText(this, "未找到该日期的壁纸", Toast.LENGTH_LONG).show();
        }
    }


    private void showLoadingState(boolean show) {
        if (binding == null) return;
        binding.progressBarBing.setVisibility(show ? View.VISIBLE : View.GONE);
        if (show) {
            binding.recyclerViewWallpapersBing.setVisibility(View.GONE);
            binding.textViewErrorBing.setVisibility(View.GONE);
        }
    }

    private void showErrorState(String message) {
        if (binding == null) return;
        binding.recyclerViewWallpapersBing.setVisibility(View.GONE);
        binding.textViewErrorBing.setText(message);
        binding.textViewErrorBing.setVisibility(View.VISIBLE);
    }


    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}